/**
 * @version 1.0
 * @author Ha Giang
 * @date
 */
package DiscoveryFunction;

import Communications.Multicast;
import Communications.UnicastClient;
import Configuration.Utils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This thread processes messages from clients
 *
 */
public class ClientsProcessorThread extends Thread {

    private ConcurrentHashMap<String, ServiceInfo> services = null;
    private Queue msgStreamClient;
    private Multicast mc;

    /**
     * Constructor
     *
     * @param _dir The Directory who creates this thread
     */
    public ClientsProcessorThread(Directory _dir) {
        mc = new Multicast();
        msgStreamClient = mc.startMulticastClientChannel();
        this.services = _dir.getServices();
    }

    /**
     * Process a query message
     * @param query Query string
     */
    public void processQuery(String query) {

        String clientIP = query.split(":")[1];
        UnicastClient uc = new UnicastClient(clientIP, Utils.UNICAST_NOTIFY_PORT);

        //send the number of services back to the client
        uc.sendMessage(String.valueOf(services.size()));
        //list
        Enumeration e = services.keys();

        //iterate through Hashtable keys Enumeration
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            ServiceInfo si = services.get(o);
            //send server's infomation back to the client 
            uc.sendMessage(si.toString());
        }
        uc.close();
    }

    @Override
    public void run() {
        String s;
        while (true) {

            while (!msgStreamClient.isEmpty()) {
                s = (String) msgStreamClient.remove();

                if (s != null) {
                    System.out.println("Directoty: Get msg from  Client channel:" + s);
                    if (s.startsWith("Query")) {
                        processQuery(s);
                    }
                }
            }

        }
    }
}
